package com.devilwwj.http.callback;

import android.util.Log;

import com.devilwwj.http.core.AbstractDataCallback;
import com.devilwwj.http.exception.HttpException;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by devilwwj on 15/7/25.
 */
public abstract class JSONCallback<T> extends AbstractDataCallback<T> {
    @Override
    public T bindData(String result) throws HttpException {
        Log.e("result", result);

        try {
            JSONObject json = new JSONObject(result);
            Object data = json.opt("data");
            Gson gson = new Gson();
            Type type = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            return gson.fromJson(data.toString(), type);
        } catch (JSONException e) {
            throw new HttpException(HttpException.ErrorType.JSON, e.getMessage());
        }
    }
}
